// ***** BEGIN LICENSE BLOCK *****
// Version: MPL 1.1/GPL 2.0/LGPL 2.1
//
// The contents of this file are subject to the Mozilla Public License Version
// 1.1 (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
// http://www.mozilla.org/MPL/
//
// Software distributed under the License is distributed on an "AS IS" basis,
// WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
// for the specific language governing rights and limitations under the
// License.
//
// The Initial Developer of the Original Code is
//   Axel Nennker http://axel.nennker.de/ .
// Created by the Initial Developer are Copyright (C) 2011
// the Initial Developer. All Rights Reserved.

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;

Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");

function log(aMessage) {
  Services.console.logStringMessage("openidConnect: " + aMessage);
}

function OpenIdConnect() {
  this.wrappedJSObject = this;
}
  
OpenIdConnect.prototype = {
  classDescription: "Component to store openids",
  classID:          Components.ID("{7d1c4024-aa69-4755-b51c-143105db26fc}"),
  contractID:       "@openinfocard.com/openidconnect;1",
  QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports]),

  getServerConfig(aUrl, aListener) {
    try {
      var hrefStr;
      var uri = Services.io.newURI(aUrl, null, null);
      hrefStr = uri.prePath + "/.well-known/openid-configuration";
      var req = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance();
      try {
        req.open('GET', hrefStr, true);
      } catch (openException) {
        aListener.onError("" + openException);
        return;
      }
      req.setRequestHeader('Content-Type', 'application/json');
      req.onreadystatechange = function (aEvent) {
        if (req.readyState == 4) {
           if (req.status != 200) {
             aListener.onError(req.statusText);
             return;
           }
           aListener.onReady(req.responseText);
        }
     };
     req.send(null);
   } catch(e) {
     try {
       aListener.onError("" + e);
     } catch (ee) {} // ignore
     Cu.reportError(e);
     throw e;
   }
  }
};

var NSGetFactory = XPCOMUtils.generateNSGetFactory([OpenIdConnect]);
